import React from 'react';
import {Spin, Card, Button, Row, Col, Table, Form} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, TABLE, DATE_FORMAT, FILES_API} from '../constants';
import {invoiceData, getDetail} from './api';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {partClaimType, currency, partClaimReasonStatus} from '../Enum';
import {injectIntl} from './intl';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import styles from './style.css';
import Return from '../common/Return';
const {Description} = DescriptionList;
const FormItem = Form.Item;

class InvoicePanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        details: []
    }
    componentDidMount() {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.details,
                    });
                else
                    this.setState({loading: false});
            });
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        if(!this.state.hasOperat)
            this.setState({
                data: {
                    ...data,
                    attachments
                },
                hasOperat: true,
            });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        if(!this.state.hasOperat)
            this.setState({
                data: {
                    ...data,
                    attachments
                },
                hasOperat: true,
            });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        this.setState({loading: true});
        const rowVersion = this.state.data.rowVersion;
        invoiceData(this.props.id, rowVersion)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, loading} = this.state;
        const {attachments = []} = data;
        const {brands} = this.props.initEnumData;
        const {isDealerUser} = this.props;
        let totalFee = 0;
        if(details)
            details.forEach(d => {
                totalFee += (d.cacuFee);
            });
        let claimtTotalFee = 0;
        if(details)
            details.forEach(d => {
                claimtTotalFee += (d.claimFee);
            });
        const columns = [{
            title: formatMessage({
                id: 'invoicePanel.column.reportCode',
                defaultMessage: '备件索赔报告编号'
            }),
            dataIndex: 'reportCode',
        }, {
            title: formatMessage({
                id: 'invoicePanel.column.claimType',
                defaultMessage: '索赔类型'
            }),
            dataIndex: 'claimType',
            render: text => conventEnumValueToString(partClaimType, text)
        }, {
            title: formatMessage({
                id: 'invoicePanel.column.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'invoicePanel.column.claimCode',
                defaultMessage: '备件索赔单编号'
            }),
            dataIndex: 'claimCode',
        }, {
            title: formatMessage({
                id: 'invoicePanel.column.packingListCode',
                defaultMessage: '箱单号'
            }),
            dataIndex: 'packingListCode',
        }, {
            title: formatMessage({
                id: 'invoicePanel.column.partSaleOrderCode',
                defaultMessage: '备件销售订单编号'
            }),
            dataIndex: 'partSaleOrderCode',
        }, {
            title: formatMessage({
                id: 'invoicePanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'invoicePanel.column.partName',
                defaultMessage: '备件中文名称'
            }),
            dataIndex: 'partName',
        }, {
            title: formatMessage({
                id: 'invoicePanel.column.cacuQuantity',
                defaultMessage: '结算数量'
            }),
            dataIndex: 'cacuQuantity',
        }, {
            title: formatMessage({
                id: 'invoicePanel.column.price',
                defaultMessage: '索赔单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'invoicePanel.column.claimReason',
                defaultMessage: '索赔原因'
            }),
            dataIndex: 'claimReason',
            render: text => conventEnumValueToString(partClaimReasonStatus, text)
        }, {
            title: formatMessage({
                id: 'invoicePanel.column.claimFee',
                defaultMessage: '赔付金额'
            }),
            dataIndex: 'claimFee',
            render: text => formatAmount(text)
        }];
        if(!this.props.isDealerUser)
            columns.splice(11, 0, ...[
                {
                    title: formatMessage({
                        id: 'invoicePanel.column.mgmtFee',
                        defaultMessage: '管理费'
                    }),
                    dataIndex: 'mgmtFee',
                    render: text => formatAmount(text)
                },
            ]);
        if(!this.props.isDealerUser)
            columns.splice(12, 0, ...[
                {
                    title: formatMessage({
                        id: 'invoicePanel.column.cacuFee',
                        defaultMessage: '结算金额'
                    }),
                    dataIndex: 'cacuFee',
                    render: text => formatAmount(text)
                },
            ]);
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'invoicePanel.column.common',
                        defaultMessage: '备件索赔结算信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'invoicePanel.operation.code',
                                        defaultMessage: '编号'
                                    })}{...FORM_OPTIONS.item}>
                                        {data.code}
                                    </FormItem>
                                </Col>
                                {brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'invoicePanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item}>
                                        ({data.brandCode}){data.brandName}
                                    </FormItem>
                                </Col>}
                                { !isDealerUser && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'invoicePanel.form.dealerId',
                                        defaultMessage: '总代'
                                    })}{...FORM_OPTIONS.item}>
                                        ({data.dealerCode}){data.dealerName}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'invoicePanel.operation.createTime',
                                        defaultMessage: '申请日期'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatDateTime(data.createTime, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                { !isDealerUser && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'invoicePanel.operation.totalFee',
                                        defaultMessage: '结算总金额'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatAmount(totalFee)}
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'invoicePanel.operation.claimtTotalFee',
                                        defaultMessage: '赔付总金额'
                                    })}{...FORM_OPTIONS.item}>
                                        {formatAmount(claimtTotalFee)}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'invoicePanel.operation.detail',
                            defaultMessage: '备件索赔结算清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={columns}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card>
                        {attachments && attachments.length > 0
                            ? <DescriptionList title={formatMessage({
                                id: 'invoicePanel.card.attachment',
                                defaultMessage: '附件清单'
                            })} size="large">
                                {attachments.map(item => (<Description key={item.fileId}>
                                    <a icon="download" download href={`${FILES_API.files}/${item.fileId}`} size="small">{item.fileName}</a></Description>))}
                            </DescriptionList>
                            : formatMessage({
                                id: 'invoicePanel.content.noAttachment',
                                defaultMessage: '暂无附件'
                            })}
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'invoicePanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

InvoicePanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryCondition,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
    isDealerUser: state.getIn((['page', 'domainData', 'init', 'isDealerUser'])),
});
const mapDispatchToProps = (dispatch, props) => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(InvoicePanel));
